
/**
 *	TrueMusic - simple java mp3 player
 *
 *	TrueMusic is free software; you can redistribute it
 *	and/or modify it under the terms of the GNU General
 *	Public License as published by the Free Software
 *	Foundation; either version 2 of the License or (at
 *	your option) any later version.
 *	
 *	This program is distributed in the hope that it will be
 *	useful but WITHOUT ANY WARRANTY; without even the 
 *	implied warranty of the MERCHANTABILITY or FITNESS FOR
 *	A PARTICULAR PURPOSE. See the GNU General Public
 *	License for more details.
 *	
 *	Copyright (c)2005-2007 Ryan Macnak <rmacnak@gmail.com>
 */

package com.servequake.truemusic;

import java.io.*;
import java.util.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import javax.xml.parsers.*;

/**
 * to be eventually replaced by Playlist
 */
public class PlaylistReader extends DefaultHandler
{
	class element
	{
		String name="";
		Map<String,String> attributes = new HashMap<String,String>();
		element parent=null;
		List<element> children = new LinkedList<element>();
		String chars="";
	}

	element current=null;
	Player p;

	PlaylistReader(File f, Player p) throws Exception
	{
		this.p=p;

		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser parser = factory.newSAXParser();
		parser.parse( new FileInputStream(f), this );
	}

	public void startElement(String namespaceURI,String sName,String qName,Attributes attrs)throws SAXException
	{
		element e = new element();
		e.name=qName;
		e.parent=current;
	
		if(attrs!=null) for(int i=0; i<attrs.getLength(); i++)
		{
			e.attributes.put( attrs.getQName(i),attrs.getValue(i) );
		}
		if(current!=null)current.children.add(e);
		current = e;
	}


	public void characters(char buf[],int offset,int len) throws SAXException
	{
		String s = new String(buf,offset,len);
		current.chars = current.chars + s;
	}

	public void endElement(String namespace, String sName, String qName) throws SAXException
	{
		element e = current;
		current = e.parent;

		if(e.name.equals("entry"))
		{
			String title="",artist="",album="",res="",frames="0",mod="0";
	
			for(element c: e.children)
			{
				if(c.name.equals("title")) title = c.chars;
				if(c.name.equals("artist")) artist = c.chars;
				if(c.name.equals("album")) album = c.chars;
				if(c.name.equals("resource")) res = c.chars;
				if(c.name.equals("frames")) frames = c.chars;
				if(c.name.equals("last-modified")) mod = c.chars;
			}

			try
			{
				p.addTrack(res,title,artist,album,frames,mod);
			}
			catch(Exception ex){ex.printStackTrace();}
		}
	}
}